using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel.Design.Serialization;
using System.CodeDom;

namespace Ferpect.GameComponents.Design.Serialization
{
    /// <summary>
    /// This class will deserialize a CodeTypeDeclaration into an instance of type T.
    /// In order for this to work, T has to support the serialized properties of the
    /// original type.
    /// 
    /// Serialization simply delegates to the standard Component serializer because it
    /// is assumed that T already serializes into something compatible with the original
    /// type. For example, T could implement ICustomTypeDescriptor so that it has all
    /// the same serializable properties as the original type.
    /// </summary>
    /// <typeparam name="T">The instance type to return from Deserialize.</typeparam>
    public class ViewTypeCodeDomSerializer<T> : TypeCodeDomSerializer
    {
        private readonly string deserializedType = typeof(T).FullName;

        public override object Deserialize(IDesignerSerializationManager manager, System.CodeDom.CodeTypeDeclaration declaration)
        {
            declaration.BaseTypes[0] = new System.CodeDom.CodeTypeReference(deserializedType);

            TypeCodeDomSerializer innerSerializer = (TypeCodeDomSerializer)manager.GetSerializer(typeof(System.ComponentModel.Component), typeof(TypeCodeDomSerializer));
            return innerSerializer.Deserialize(manager, declaration);
        }

        public override System.CodeDom.CodeTypeDeclaration Serialize(IDesignerSerializationManager manager, object root, System.Collections.ICollection members)
        {
            TypeCodeDomSerializer innerSerializer = (TypeCodeDomSerializer)manager.GetSerializer(typeof(System.ComponentModel.Component), typeof(TypeCodeDomSerializer));
            CodeTypeDeclaration declaration = innerSerializer.Serialize(manager, root, members);

            return declaration;
        }
    }
}
